package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import com.sky.vo.TreeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 添加菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(DishDTO dishDTO) {
        // 创建dish和dishFlavor实体类
        Dish dish = new Dish();
        // 将传入的数据拷贝到dish中
        BeanUtils.copyProperties(dishDTO, dish);
        // 设置启售状态
        dish.setStatus(StatusConstant.ENABLE);
        // 执行sql语句
        dishMapper.insert(dish);
        // 获取插入数据后的dishId
        Long dishId = dish.getId();
        // 获取口味的数据，添加到口味表里面
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if (flavorList != null && flavorList.size() > 0) {
            for (DishFlavor flavor : flavorList) {
                flavor.setDishId(dish.getId());
            }
            log.info("flavorList是：{}", flavorList);
            dishFlavorMapper.insertBatch(flavorList);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        // 查询分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 获取分页数据
        Page<DishVO> page = dishMapper.page(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 菜品起售停售
     *
     * @param dish
     */
    @Override
    public void updateStatus(Dish dish) {
        dishMapper.updateStatus(dish);
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getDishById(Long id) {
        DishVO dishVO = dishMapper.getDishById(id);
        // 获取口味的数据
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getDishFlavorById(id);
        // 将数据拷贝到dish表里面
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        // 创建Dish对象
        Dish dish = new Dish();
        // 拷贝到dish对象里面
        BeanUtils.copyProperties(dishDTO, dish);
        // 更新菜品
        dishMapper.updateStatus(dish);
        // 删除原来的菜品口味
        dishFlavorMapper.deleteById(dish.getId());
        // 插入新的口味
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if (flavorList != null && flavorList.size() > 0) {
            for (DishFlavor flavor : flavorList) {
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insertBatch(flavorList);
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        return dishMapper.list(categoryId);
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Long> ids) {
        // 判断当前删除的是否是有启售状态
        for (Long id : ids) {
            DishVO dishVO = dishMapper.getDishById(id);
            if (dishVO.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 判断当前菜品是否关联了套餐
        List<Long> setmealDishIds = setmealDishMapper.getSetmealDishIds(ids);
        if (setmealDishIds != null && setmealDishIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        File file = new File("C:\\Users\\14467\\Desktop\\java\\code\\sky-take-out\\sky-server\\src\\main\\resources\\images");
        File[] files = file.listFiles();
        // 创建文件名称集合
        List<String> fileList = new ArrayList<>();
        for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
            String fileName = "/" + Objects.requireNonNull(files)[i].getName();
            fileList.add(fileName);
        }
        for (Long id : ids) {
            DishVO dishVO = dishMapper.getDishById(id);
            // 获取文件名称
            String imageName = dishVO.getImage().substring(dishVO.getImage().lastIndexOf("/"));
            if (fileList.contains(imageName)) {
                // 删除图片
                File deleteFile = new File("C:\\Users\\14467\\Desktop\\java\\code\\sky-take-out\\sky-server\\src\\main\\resources\\images\\" + imageName);
                deleteFile.delete();
            }
        }
        // 删除当前菜品
        dishMapper.deleteBatch(ids);
        // 删除每个菜品的口味
        for (Long id : ids) {
            dishFlavorMapper.deleteById(id);
        }
    }

    /**
     * 获取树结构
     *
     * @return
     */
    @Override
    public List<TreeVo> getTree() {
        // 定义数组
        ArrayList<TreeVo> list = new ArrayList<>();
        // 获取分类数据
        List<Category> categoryList = categoryMapper.list(StatusConstant.ENABLE);
        // 遍历数据
        for (Category category : categoryList) {
            // 获取每个分类下面的菜品
            List<Dish> dishList = dishMapper.list(category.getId());
            // 获取TreeVo对象
            TreeVo treeVo = new TreeVo();
            treeVo.setId(category.getId());
            treeVo.setName(category.getName());
            treeVo.setIsLeaf(false);
            treeVo.setChildren(dishList);
            list.add(treeVo);
        }
        return list;
    }

    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        final List<DishVO> dishVOList = new ArrayList<>();
        List<Dish> dishList = dishMapper.list(categoryId);
        for (Dish dish : dishList) {
            DishVO dishVO = new DishVO();
            List<DishFlavor> flavorList = dishFlavorMapper.getDishFlavorById(dish.getId());
            BeanUtils.copyProperties(dish,dishVO);
            dishVO.setFlavors(flavorList);
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }
}
